import React, { useState } from 'react';
import { Checkbox, Row, Col } from 'antd';

export default function CheckLists(props) {
  const [checked, setCheck] = useState(false);
  const [indeterminate, setIndeterminate] = useState(false);

  const [data, setData] = useState([]);

  function onChange(checkedValues) {
    // console.log(1)
    setData(checkedValues);
    const is_indeterminate = !!checkedValues.length && checkedValues.length < props.options.length;
    setIndeterminate(is_indeterminate);
    setCheck(checkedValues.length === props.options.length);
    handleChange(checkedValues);
  }

  function onChangeAll(e) {
    setCheck(e.target.checked);
    setIndeterminate(false)
    if (e.target.checked) {
      const data = props.options.map(item => item.code);
      setData(data);
      handleChange(data);
    } else {
      setData([]);
      handleChange([]);
    }
  }

  function handleChange(value) {
    props.onChange && props.onChange(value);
  }
  return (
    <div style={{ padding: '20px 0' }}>
      <p style={{ marginBottom: '10px' }}>
        {props.title}
        <Checkbox
          onChange={onChangeAll}
          checked={checked}
          indeterminate={indeterminate}
          style={{ marginLeft: '10px' }}
        ></Checkbox>
      </p>

      <Checkbox.Group onChange={onChange} value={data} style={{ width: '100%' }}>
        <Row gutter={10}>
          {props.options.map(item => {
            return (
              <Col key={item.code} span={6} style={{ margin: '5px 0' }}>
                <Checkbox value={item.code}>{item.name}</Checkbox>
              </Col>
            );
          })}
        </Row>
      </Checkbox.Group>
    </div>
  );
}
